package cn.wmingming.e3mall.search.dao;

import cn.wmingming.common.pojo.SearchItem;
import cn.wmingming.common.pojo.SearchResult;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Huangzm
 * @create 2018/05/27 0:59
 * @desc
 * @Modified By:
 **/
@Repository
public class SolrQueryDao {

    @Autowired
    private SolrServer solrServer;
    public SearchResult search(SolrQuery query) throws SolrServerException {
        //根据查询条件查询索引库
        QueryResponse queryResponse = solrServer.query(query);
        //取商品列表
        SolrDocumentList responseResults = queryResponse.getResults();
        //取查询结果总记录数
        long numFound = responseResults.getNumFound();
        //创建一个结果返回对象
        SearchResult searchResult = new SearchResult();
        searchResult.setRecordCount(numFound);
        //创建商品列表对象
        List<SearchItem> searchItemList = new ArrayList<>();
        //取高亮后的结果
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        for(SolrDocument document:responseResults){
            //取商品信息
            SearchItem searchItem = new SearchItem();
            searchItem.setCategory_name((String)document.get("item_category_name"));
            searchItem.setId((String) document.get("id"));
            searchItem.setImage((String) document.get("item_image"));
            searchItem.setPrice((Long) document.get("item_price"));
            searchItem.setSell_point((String) document.get("item_sell_point"));
            //取高亮的标题
            List<String> titleList = highlighting.get(document.get("id")).get("item_title");
            String title = "";
            if(titleList != null && titleList.size() > 0){
                title = titleList.get(0);
            }else {
                title = (String) document.get("item_title");
            }
            searchItem.setTitle(title);
            searchItemList.add(searchItem);
        }
        searchResult.setItemList(searchItemList);
        return searchResult;
    }
}
